package com.hermit.qmst.adapter;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.hermit.qmst.R;
import com.hermit.qmst.mode.GridItemInfo;
import com.hermit.qmst.tools.Common;
import com.hermit.qmst.tools.ImageDownLoader;

import java.util.List;

/**
 * Created by hermithermit on 15/3/31.
 */
public class GridViewAdapter extends BaseAdapter {


    private Activity mContext;
    private List<GridItemInfo> mGridItemInfoList;
    private ImageDownLoader mImageDownLoader;

    public GridViewAdapter(Activity context,List<GridItemInfo> gridItemInfoListList){
        mContext = context;
        mGridItemInfoList = gridItemInfoListList;
        mImageDownLoader = new ImageDownLoader(mContext);
    }

    @Override
    public int getCount() {
        return mGridItemInfoList.size();
    }


    @Override
    public Object getItem(int position) {
        return mGridItemInfoList.get(position);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }


    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

          Hodler hodler = null;

        if (convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_gridview,null);
            hodler = new Hodler();
            hodler.imageView = (ImageView)convertView.findViewById(R.id.iv_g_item);
            hodler.textView = (TextView)convertView.findViewById(R.id.tv_g_item);
            convertView.setTag(hodler);
        }else {
            hodler = (Hodler)convertView.getTag();
        }

        final ImageView imageView = hodler.imageView;

        GridItemInfo info = (GridItemInfo)mGridItemInfoList.get(position);

        hodler.textView.setText(info.getTitle());
        Bitmap bitmap = mImageDownLoader.downloadImage(Common.getDialImageDirPath(),info.getImageUrl(),new ImageDownLoader.onImageLoaderListener() {
            @Override
            public void onImageLoader(Bitmap bitmap, String url) {
                Drawable drawable = new BitmapDrawable(mContext.getResources(),bitmap);
                imageView.setBackgroundDrawable(drawable);
                notifyDataSetChanged();
            }
        });

        if (bitmap != null){
            hodler.imageView.setBackgroundDrawable(new BitmapDrawable(mContext.getResources(),bitmap));
        }



        return convertView;
    }

    private class Hodler{
        private ImageView imageView;
        private TextView textView;
    }
}
